/*
 * @Author: jiu yin
 * @Date: 2024-04-09 11:39:45
 * @LastEditTime: 2024-04-26 17:30:40
 * @LastEditors: jiu yin zhen jing
 * @FilePath: \web-smart-tour\src\utils\index.js
 * jiu
 */
import { redirectTo } from '@/hooks';
import { login, appletUserInfo, appletPhone, uploadSignature } from '@/api/home.js';
import store from '@/store';

export const screenWidth = uni.getSystemInfoSync().screenWidth;
export const screenHeight = uni.getSystemInfoSync().screenHeight;

//uni的获取
export const getToken = () => {
	return uni.getStorageSync('token');
};
export const setToken = (str) => {
	return uni.setStorageSync('token', str);
};

/**
 * 格式化
 * @param { Date } day
 * @param { String } fmt
 * @returns { String } time
 */
export function parseTime(time, cFormat) {
	if (arguments.length === 0 || !time) {
		return null;
	}
	const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
	let date;
	if (typeof time === 'object') {
		date = time;
	} else {
		if (typeof time === 'string') {
			if (/^[0-9]+$/.test(time)) {
				// support "1548221490638"
				time = parseInt(time);
			} else {
				time = time.replace(new RegExp(/-/gm), '/');
			}
		}

		if (typeof time === 'number' && time.toString().length === 10) {
			time = time * 1000;
		}
		date = new Date(time);
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay(),
	};
	const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
		const value = formatObj[key];
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') {
			return ['日', '一', '二', '三', '四', '五', '六'][value];
		}
		return value.toString().padStart(2, '0');
	});
	return time_str;
}

//防抖
export const debounce = () => {
	let time = null;
	return function (callback = () => {}, delayed = 300) {
		if (time) clearTimeout(time);
		time = setTimeout(() => {
			callback();
		}, delayed);
	};
};
//节流
export const throttle = () => {
	let is_pass = true;
	return function (callback = () => {}, delayed = 300) {
		if (!is_pass) return;
		is_pass = false;
		setTimeout(() => {
			console.log('我是打野的');
			callback();
			is_pass = true;
		}, delayed);
	};
};
//范围随机数
export const range_random = (min, max) => {
	return Math.floor(Math.random() * (max - min + 1) + min);
};

// 登录弹窗
export const getPhone = (event) => {
	const that = this;
	if (event.detail.errMsg === 'getPhoneNumber:ok') {
		uni.showLoading({
			title: '登录中...',
			mask: true,
			fail: () => {
				uni.hideLoading();
			},
		});
		uni.login({
			provider: 'weixin',
			success(loginRes) {
				console.log('[  loginRes.code ] >', loginRes);
				uni.getUserInfo({
					success: (res) => {
						// 登录
						let params = {
							login_type: 'applet',
							js_code: loginRes.code,
						};
						login(params).then(async (data) => {
							// 存储token
							setToken(data.data.token);

							//小程序用户手机号完善
							await appletPhone({ phone_code: event.detail.code });

							// // 小程序用户信息完善
							// let infoParams = {
							//     nick_name: res.userInfo.nickName,
							//     avatar: res.userInfo.avatarUrl
							// }
							// appletUserInfo(infoParams);

							store.commit('userInfo/set_user_info', data.data);
							store.commit('userInfo/set_is_login_popup', false);
							setTimeout(() => {
								store.commit('userInfo/set_is_login_disabled', false);
							}, 1000);
							console.log('设置关闭弹框');
							redirectTo_url();
						});
					},
					fail: function (res) {
						// vm.$store.commit("", false);
						store.commit('userInfo/set_is_login_disabled', false);
					},
					complete: () => {
						uni.hideLoading();
					},
				});
			},
			fail: () => {
				uni.hideLoading();
			},
		});
	} else {
		store.commit('userInfo/set_is_login_popup', false);
	}
};

// 刷新当前页
const reload = () => {
	// 页面重载
	const pages = getCurrentPages();
	// 声明一个pages使用getCurrentPages方法
	const curPage = pages[pages.length - 1];
	// 声明一个当前页面
	curPage.onLoad(curPage.options); // 传入参数
	curPage.onShow();
	// 执行刷新
	curPage.onReady();
};

//redirectTo_重载当前页
export const redirectTo_url = () => {
	const pages = getCurrentPages();
	const curPage = pages[pages.length - 1];
	redirectTo(curPage.$page.fullPath);
};

// 支付
export const payNow = (res, callback = () => {}) => {
	uni.requestPayment({
		provider: 'wxpay',
		appId: res.appId,
		timeStamp: res.timestamp,
		nonceStr: res.nonceStr,
		package: res.package,
		signType: res.signType,
		paySign: res.paySign,
		success: function (res) {
			uni.showModal({
				content: '支付成功',
				showCancel: false,
				success() {
					callback();
				},
			});
		},
		fail: function (err) {
			uni.showModal({
				content: '支付已取消',
				showCancel: false,
				success() {},
			});
		},
	});
};

//上传
export const uploadFile = (obj = {}) => {
	let { url, filePath, name, file, formData } = obj;

	// 上传音频文件到服务器上
	function upload(resolve, reject) {
		uni.uploadFile({
			url,
			filePath,
			name: name || 'file',
			fileType: 'image/video/audio',
			file: file || {},
			header: {
				'token': getToken(),
				'content-type': 'multipart/form-data',
			},
			formData: formData || {},
			success: (uploadFileRes) => {
				resolve(JSON.parse(uploadFileRes.data));
			},
			fail: (err) => {
				console.log(err, '上传失败了');
				reject(err);
			},
		});
	}

	return new Promise(upload);
};

//获取图片信息
export function getImgInfo(filePath) {
	function getInfo(resolve, reject) {
		uni.getImageInfo({
			src: filePath,
			success: function (image) {
				resolve(image);
			},
			fail: (res) => {
				reject(res);
			},
		});
	}
	return new Promise(getInfo);
}

export function compressImg(filePath, config = {}) {
	const { width = '', quality = 80 } = config;
	return new Promise((resolve, reject) => {
		uni.compressImage({
			...config,
			src: filePath,
			success: (res) => {
				resolve(res.tempFilePath);
			},
			fail: (res) => {
				reject(res);
			},
		});
	});
}
export function errToast(err) {
	uni.showModal({
		title: '提示',
		content: JSON.stringify(err),
		success: function (res) {
			if (res.confirm) {
				console.log('用户点击确定');
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		},
	});
}


//photo上传
export const photoUploadFile = (filePath, filename = '',scene='') => {
	
	return new Promise(async (resolve, reject) => {
		const { data: ossConfig = {} } = await uploadSignature({ scene:scene, appoint: 1, filename });
		const accessId = ossConfig.accessId;
		
		
		if (!accessId) {
			reject({ msg: '上传失败~!' });
			return;
		}
		console.log('ossConfig==', ossConfig);
		let file_url = ossConfig.dir ? ossConfig.dir + (filename ? '/' + filename : '') : ossConfig.key;
		file_url = `/${file_url}`;
		
		const fileName = ossConfig.fileName;
		let ossUrl = ossConfig.host;
		const key = ossConfig.dir ? ossConfig.dir + (fileName ? '/' + fileName : '') : ossConfig.key;
		console.log(key, '===ke===');
		uni.uploadFile({
			url: ossUrl, //输入你的bucketname.endpoint
			filePath: filePath,
			fileType: ossConfig.fileType,
			name: 'file',
			timeout: 60000,
			formData: {
				// name: nameStr,
				key: key,
				OSSAccessKeyId: ossConfig.accessId,
				policy: ossConfig.policy, // 输入你获取的的policy
				success_action_status: '200', // 让服务端返回200,不然，默认会返回204
				signature: ossConfig.signature, // 输入你获取的的signature
			},
			success: (res) => {
				const { statusCode = 0 } = res;
				if (statusCode != 200) {
					reject({ res, msg: '上传失败!!' });
					return;
				}
				res.file_url = file_url;
				resolve(res);
			},
			fail: (res) => {
				// errToast('err' + ossConfig.host + JSON.stringify(res));
				console.log('上传失败==', res);
				reject(res);
			},
		});
	});
};

//oss直传
export const ossUploadFile = (filePath, filename = '') => {
	return new Promise(async (resolve, reject) => {
		const { data: ossConfig = {} } = await uploadSignature({ scene: 'ai_identify', appoint: 1, filename });
		const accessId = ossConfig.accessId;
		
		if (!accessId) {
			reject({ msg: '上传失败~!' });
			return;
		}
		console.log('ossConfig==', ossConfig);
		let file_url = ossConfig.dir ? ossConfig.dir + (filename ? '/' + filename : '') : ossConfig.key;
		file_url = `/${file_url}`;

		const fileName = ossConfig.fileName;
		let ossUrl = ossConfig.host;
		const key = ossConfig.dir ? ossConfig.dir + (fileName ? '/' + fileName : '') : ossConfig.key;
		console.log(key, '===ke===');
		uni.uploadFile({
			url: ossUrl, //输入你的bucketname.endpoint
			filePath: filePath,
			fileType: ossConfig.fileType,
			name: 'file',
			timeout: 60000,
			formData: {
				// name: nameStr,
				key: key,
				OSSAccessKeyId: ossConfig.accessId,
				policy: ossConfig.policy, // 输入你获取的的policy
				success_action_status: '200', // 让服务端返回200,不然，默认会返回204
				signature: ossConfig.signature, // 输入你获取的的signature
			},
			success: (res) => {
				const { statusCode = 0 } = res;
				if (statusCode != 200) {
					reject({ res, msg: '上传失败!!' });
					return;
				}
				res.file_url = file_url;
				resolve(res);
			},
			fail: (res) => {
				// errToast('err' + ossConfig.host + JSON.stringify(res));
				console.log('上传失败==', res);
				reject(res);
			},
		});
	});
};

//是否授权
export const getSetting = ({ scope, url, content, toast }) => {
	function resolve(resolve, reject) {
		uni.getSetting({
			success: (res) => {
				if (res.authSetting[scope]) {
					// 已经授权，可以直接调用获取位置信息的方法
					resolve();
				} else {
					uni.authorize({
						scope,
						success() {
							resolve();
						},
						fail() {
							uni.showModal({
								title: '提示',
								content,
								success: function (res) {
									if (res.confirm) {
										uni.openSetting({
											success: (res) => {
												if (res.authSetting[scope]) {
													uni.redirectTo({ url });
													resolve();
												} else {
													uni.$u.toast(toast);
													reject(scope + '授权失败');
												}
											},
										});
									} else {
										uni.$u.toast(toast);
										reject(scope + '授权失败');
									}
								},
								fail() {
									uni.$u.toast(toast);
									reject(scope + '授权失败');
								},
							});
						},
					});
				}
			},
		});
	}

	return new Promise(resolve);
};

// rpx转px
export function rpxToPx(rpx) {
	return (screenWidth * Number.parseInt(rpx)) / 750;
}

// px转rpx
export function pxToRpx(px) {
	return (750 * Number.parseInt(px)) / screenWidth;
}

export function ossurl(url, type = '') {
	const domain_url = store.getters?.rec_url;
	const user_default_avatar = store.getters.fileDeploy?.user?.avatar;
	let result_url = '';
	if (/^data:image\//.test(url)) {
		result_url = url;
	} else if (/^(http|https):\/\/.+/.test(url) || /^\/\/.+/.test(url)) {
		result_url = url;
	} else {
		result_url = domain_url + url;
	}
	if (['user_avatar', 'user_face'].includes(type) && url == '') {
		result_url = result_url + user_default_avatar;
	}
	return result_url;
}

/**
 * 向上找到最近的指定组件——findComponentUpward
 * @param {VueComponent} context
 * @param {String} componentName
 * @returns
 */
export function findComponentUpward(context, componentName) {
	let parent = context.$parent;
	let name = parent?.$options.name;

	while (parent && (!name || [componentName].indexOf(name) < 0)) {
		parent = parent.$parent;
		if (parent) {
			name = parent?.$options.name;
		}
	}
	return parent;
}

/**
 * 向下找到最近的指定组件——findComponentDownward
 * @param {VueComponent} context
 * @param {String} componentName
 * @returns
 */
export function findComponentDownward(context, componentName) {
	const childrens = context.$children;
	let children = null;
	if (childrens.length) {
		for (const child of childrens) {
			const name = child?.$options.name;

			if (name === componentName) {
				children = child;
				break;
			} else {
				children = findComponentDownward(child, componentName);
				if (children) break;
			}
		}
	}
	return children;
}
